<template>
  <div ref="chartContainer" :id="props.id" class="jnpf-univer-echart-ele" />
</template>

<script lang="ts" setup>
  import { onMounted, onBeforeUnmount, ref, watch } from 'vue';
  import { storeToRefs } from 'pinia';
  import * as echarts from 'echarts';
  import { debounce } from 'lodash-es';
  import { useJnpfUniverStore } from '../../../store';

  defineOptions({ name: 'JnpfUniverEchart' });

  interface PropsType {
    id: string;
    piniaStoreId: string;
  }
  const props = defineProps<PropsType>();
  const chartContainer = ref<HTMLDivElement | null>(null);

  const jnpfUniverStore = useJnpfUniverStore(props.piniaStoreId);
  const { modeCache, focusEchartItemCache, echartImgItemsCache } = storeToRefs(jnpfUniverStore);

  let chartInstance: echarts.ECharts | null = null;
  let resizeObserver: ResizeObserver | null = null;

  // 处理窗口大小变化的函数，带防抖
  const handleResize = debounce(() => {
    chartInstance?.resize();
  }, 300);

  // 初始化或更新图表
  function initializeChart(option: echarts.EChartsOption) {
    if (!chartContainer.value) return;

    if (!chartInstance) {
      chartInstance = echarts.init(chartContainer.value);
    }

    try {
      chartInstance.clear();

      // 使用传入的 options 配置图表
      chartInstance.setOption(option);

      // 非设计状态下，图表直接转成图片
      if (modeCache.value !== 'design') {
        const { id: domId } = props ?? {};
        if (domId) {
          try {
            const chartImgUrl = chartInstance.getDataURL({
              type: 'jpeg',
              backgroundColor: '#fff',
            });

            const updateEchartImgItemsCache = {
              ...echartImgItemsCache.value,
              [domId]: chartImgUrl,
            };

            jnpfUniverStore?.updateEchartImgItems(updateEchartImgItemsCache);
          } catch (e) {}
        }
      }

      // 设置 ResizeObserver 监听容器大小变化
      if (!resizeObserver) {
        resizeObserver = new ResizeObserver(handleResize);
        resizeObserver.observe(chartContainer.value);
      }
    } catch (e) {
      console.error(`图表生成失败：${e}`);
    }
  }

  onMounted(() => {
    const { id: domId, piniaStoreId } = props ?? {};
    if (!chartContainer.value || !domId || !piniaStoreId) return;

    const echartItems = jnpfUniverStore?.echartItemsCache ?? {};

    const option = Object.values(echartItems as Record<string, { domId: string; option: any }>)?.find(item => item?.domId === domId)?.option;

    initializeChart(option);
  });

  onBeforeUnmount(() => {
    if (resizeObserver && chartContainer.value) {
      resizeObserver.unobserve(chartContainer.value);
    }
    resizeObserver?.disconnect();
    chartInstance?.dispose();
  });

  watch(
    () => focusEchartItemCache.value,
    value => {
      const { domId, drawingId, option } = value;
      if (!domId && !drawingId) {
        // store置空的情况下，不响应
        return;
      }

      const containerId = chartContainer.value?.getAttribute('id');
      if (domId !== containerId) {
        return;
      }

      initializeChart(option);
    },
  );
</script>

<style lang="less" scoped>
  .jnpf-univer-echart-ele {
    position: absolute;
    width: 100%;
    height: 100%;
    background: #fff;
  }
</style>
